package notifyandwait;


import java.io.Serializable;
import java.util.Objects;

/**
 * Created by 5406160@qq.com on LiBoWen 李博闻.
 *
 * @ClassName : Cook
 * @Author : 54061
 * @Date: 2022/2/15 18:36
 */
public class Cook extends Thread implements Serializable {
    private static final long serialVersionUID = -8442399579136571537L;
    //包子的属性
    private BaoZi bz;

    public Cook() {
    }

    public Cook(String name) {
        super(name);
    }

    public Cook(BaoZi bz) {
        this.bz = bz;
    }

    public Cook(String name, BaoZi bz) {
        super(name);
        this.bz = bz;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public BaoZi getBz() {
        return bz;
    }

    public void setBz(BaoZi bz) {
        this.bz = bz;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Cook cook = (Cook) o;
        return Objects.equals(bz, cook.bz);
    }

    @Override
    public int hashCode() {
        return Objects.hash(bz);
    }

    @Override
    public String toString() {
        return "Cook{" +
                "bz=" + bz +
                '}';
    }
    int count = 0;

    @Override
    public void run() {
        //厨师一直做
        while (true){
            //同步代码块
            synchronized (bz){
                //什么时候厨师需要休息,有包子
                if (bz.isFlag()){
                    //厨师线程休眠
                    try {
                        bz.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //能下来说明没包子 包子状态是false
                //对包子的馅属性进行赋值
                if (count%2==0){
                    //偶数次做包子
                    bz.setXianer("茴香肉末馅");
                }else{
                    //奇数次做包子
                    bz.setXianer("西葫芦鸡蛋馅");
                }
                //统计变量要自增
                count++;
                System.out.println("姓名是"+getName()+"的厨师正在做"+bz.getXianer()+"的包子.稍等片刻");
                //假设做包子需要5秒
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(bz.getXianer()+"的包子出笼了 快来抢购啊");
                //真正做包子的代码是设置包子的状态
                bz.setFlag(true);
                //唤醒顾客线程
                bz.notifyAll();
            }
        }
    }
}
